package jarvis.utils;

import java.io.IOException;
import java.util.Properties;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;

public class ESClientFactory {

	public static Client getClient() {
		Properties props = new Properties();
		try {
			props.load(ESClientFactory.class.getClassLoader()
					.getResourceAsStream("esClient.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (props.getProperty("useInProcessNode", "true").equals("true")) {
			return getNodeClient();
		}
		return getTransportClient(
				props.getProperty("esHost:localhost", "localhost"),
				props.getProperty("esPort", "9300"));
	}

	private static Client getTransportClient(String host, String port) {
		Settings settings = ImmutableSettings.settingsBuilder()
				.put("cluster.name", "nipun").put("node.name", "nipun").build();
		return new TransportClient(settings)
				.addTransportAddress(new InetSocketTransportAddress(host,
						Integer.parseInt(port)));
	}

	private static Node node;

	synchronized private static Client getNodeClient() {
		if (node == null) {
			node = new NodeBuilder().node();
		}
		return node.client();
	}
}
